﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Net.Mail;
using System.Data.SqlServerCe;
using System.Data;
using System.Windows.Documents;
using System.Threading;
using System.Net;
using System.IO;
/**
 * KHALFAOUI Mahdi - Eleria.fr
 * 
 * */

namespace EleriaMailing
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            Intro introW = new Intro();
            introW.AllowsTransparency = true;
            introW.ShowDialog();
            InitializeComponent();
        }
        // l'adapter et le dataset sont utilisé dans toute la classe
        EleriaMailing.EleriaMailingBDDataSetTableAdapters.societeTableAdapter eleriaMailingBDDataSetsocieteTableAdapter = new EleriaMailing.EleriaMailingBDDataSetTableAdapters.societeTableAdapter();
        EleriaMailing.EleriaMailingBDDataSet eleriaMailingBDDataSet;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            eleriaMailingBDDataSet = ((EleriaMailing.EleriaMailingBDDataSet)(this.FindResource("eleriaMailingBDDataSet")));
            // Chargez les données dans la table societe. Vous pouvez modifier ce code si nécessaire.
            eleriaMailingBDDataSetsocieteTableAdapter.Fill(eleriaMailingBDDataSet.societe);
            System.Windows.Data.CollectionViewSource societeViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("societeViewSource")));
            societeViewSource.View.MoveCurrentToLast();
            tYPEPROSPECTTextBox.Text = "0";
            tb_email.Text = Properties.Settings.Default.email;
            passwordBox1.Password = Properties.Settings.Default.stmpacc;
            tb_smtp.Text = Properties.Settings.Default.smtp;
            tb_portsmtp.Text = Properties.Settings.Default.stmpport;
            tb_urlNavig.Text = "http://www.Eleria.fr";
            webBrowser1.Navigate(new Uri("http://www.eleria.fr", UriKind.RelativeOrAbsolute));
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            eleriaMailingBDDataSetsocieteTableAdapter.Insert(sOCIETETextBox.Text.ToString(), nOMCONTACTTextBox.Text.ToString(), pRENOMCONTACTTextBox.Text.ToString(), gENRECheckBox.IsChecked, eMAILTextBox.Text.ToString(), tYPEPROSPECTTextBox.Text.ToString());
            eleriaMailingBDDataSetsocieteTableAdapter.Fill(eleriaMailingBDDataSet.societe);
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            eleriaMailingBDDataSetsocieteTableAdapter.Update(eleriaMailingBDDataSet);
        }
        
   
        // Envoie des emails
        private void envoyer_Click(object sender, RoutedEventArgs e)
        {
            MailMessage mail;
            SmtpClient client = new SmtpClient(tb_smtp.Text.ToString()); // pour l'envoie du courielle
            client.Port = 587; // num port clients , // 25 pour les serveurs
            client.Credentials = new System.Net.NetworkCredential(tb_email.Text.ToString(), passwordBox1.Password.ToString()); // recuperation de @ mail ,le mot de passe 
            client.EnableSsl = true;
            try
            {
                SqlCeConnection sqlCon = new SqlCeConnection(Properties.Settings.Default.EleriaMailingBDConnectionString);
                sqlCon.Open();
                SqlCeCommand cmd = new SqlCeCommand();
                cmd.Connection = sqlCon;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT EMAIL,SOCIETE,NOMCONTACT,PRENOMCONTACT,GENRE,EMAIL from societe";
              
                SqlCeDataReader reader = cmd.ExecuteReader();
                string contenuMail = new TextRange(editContenu.rtb_ContenuEmail.Document.ContentStart, editContenu.rtb_ContenuEmail.Document.ContentEnd).Text;
                string email;
                // On boucle sur tous les emails de la BD
                while (reader.Read())
                {
                    // On remplace dans les chaines de caracteres les occurences des termes spécifiques au destinataire
                    email = contenuMail.Replace("[SOCIETE]", reader[1].ToString());
                    email = email.Replace("[NOM]", reader[2].ToString());
                    email = email.Replace("[PRENOM]", reader[3].ToString());
                    if ((bool)reader[4] == true)
                        email = email.Replace("[GENRE]", "M.");
                    else
                        email = email.Replace("[GENRE]", "Mme");
                    email = email.Replace("[EMAIL]", reader[5].ToString());
                    mail = new MailMessage(tb_email.Text.ToString(), reader[0].ToString(), editContenu.tb_titre.Text, email);
                 //  mail.DeliveryNotificationOptions ;
                    mail.BodyEncoding = Encoding.UTF8;
                    if (editContenu.tb_fichierJoint.Text.Length > 1) // s'il y a une pièce jointe stipulée, on l'ajoute
                    {
                        Attachment pieceJointe = new Attachment(editContenu.tb_fichierJoint.Text);
                        mail.Attachments.Add(pieceJointe);
                    }
                    client.Port = int.Parse(tb_portsmtp.Text.ToString()); // num port clients , // 25 pour les serveurs
                    client.Credentials = new System.Net.NetworkCredential(tb_email.Text.ToString(), passwordBox1.Password.ToString()); // recuperation de @ mail ,le mot de passe 
                    client.EnableSsl = true;
                    client.Send(mail); // envoie de l'email                        
                }
                MessageBox.Show("E-mails envoyés.");
                sqlCon.Dispose();
                cmd.Dispose();
                sqlCon.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        // Enregistrement des textBox en parametres ( smpt, login, pasww )...
        private void bt_save_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.email = tb_email.Text;
            Properties.Settings.Default.stmpacc = passwordBox1.Password;
            Properties.Settings.Default.smtp = tb_smtp.Text;
            Properties.Settings.Default.stmpport = tb_portsmtp.Text ;
            Properties.Settings.Default.Save();
        }

        public string[] ExtractionEmails(string str)
        {
            string RegexPattern = @"\b[A-Z0-9._-]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z.]{2,6}\b";
            System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(str, RegexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            string[] MatchList = new string[matches.Count];
            int c = 0;
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                MatchList[c] = match.ToString();
                c++;
            }
            return MatchList;
        }

        private string[] enleveDoublon(string[] liste)
        {
            liste= liste.Distinct().ToArray();
            return liste;
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string contenu;
            try
            {
                if (rb_texte.IsChecked == true)
                {
                    contenu = System.IO.File.ReadAllText(tb_url.Text.ToString());
                }
                else
                {
                    WebClient client = new WebClient();
                    contenu = client.DownloadString(tb_url.Text.ToString());
                }
                string[] emails = ExtractionEmails(contenu);
               emails= enleveDoublon(emails);
                SqlCeConnection sqlCon = new SqlCeConnection(Properties.Settings.Default.EleriaMailingBDConnectionString);
                sqlCon.Open();
                SqlCeCommand cmd = new SqlCeCommand();
                cmd.Connection = sqlCon;
                cmd.CommandType = CommandType.Text;
                foreach (string email in emails)
                {
                    cmd.CommandText = "INSERT INTO societe (EMAIL) VALUES ('" + email + "') ";
                    cmd.ExecuteNonQuery();
                }
                sqlCon.Dispose();
                cmd.Dispose();
                sqlCon.Dispose();
            }
            catch (Exception ex)
            {
                // handle error
                MessageBox.Show(ex.Message);
            }

        }

        private void rb_texte_Checked(object sender, RoutedEventArgs e)
        {
            if (rb_texte.IsChecked == true)
                bt_browser.Visibility = Visibility.Visible;
            else
                bt_browser.Visibility = Visibility.Hidden;
        }

        private void bt_browser_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".txt";
            dlg.Filter = "Fichier |*.txt";
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string filename = dlg.FileName;
                tb_url.Text = filename;
            }
        }

        private void rb_web_Checked(object sender, RoutedEventArgs e)
        {
            if (rb_texte.IsChecked == false)
                bt_browser.Visibility = Visibility.Hidden;
            else
                bt_browser.Visibility = Visibility.Visible;
        }

        private void bt_navig_Click(object sender, RoutedEventArgs e)
        {
            webBrowser1.Navigate(new Uri(tb_urlNavig.Text.ToString(), UriKind.RelativeOrAbsolute));
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            tb_url.Text = tb_urlNavig.Text.ToString();
        }
    }
}
